print("进程初始化……")

import os
import sys
import time

from random import random
from pathlib import Path
from PIL import Image
from multiprocessing import freeze_support

from utils.ConsoleIO import bool_str, format_ipt, ipt, prt
from utils.Constants import ADAPT, FILE_SAVE_SUFFIX, FILL
from utils.McStructure import SingleCommand, commands_to_structure
from utils.MediaOperation import (
    image_list_2_string,
    vedio_frame_split,
)

__version__ = "1.5.1"


def main():

    prt("完成！当前版本：", __version__)

    frame_list = output_file_name = None

    if sys.argv.__len__() > 1:
        # 读取缓存
        if (
            os.path.isfile(sys.argv[1])
            and os.path.splitext(sys.argv[1])[1].upper() == f".{FILE_SAVE_SUFFIX}"
        ):
            prt("暂不支持读取。")

        elif os.path.isdir(sys.argv[1]):

            if (idx_file := ((read_pth := Path(sys.argv[1])) / "CACHE_IDX")).exists():
                frame_list = [
                    (
                        (
                            read_pth / "{}.{}.RAW".format(i, FILE_SAVE_SUFFIX)
                        ).read_bytes(),
                        (
                            cot_inf := (
                                read_pth / "{}.{}.COT".format(i, FILE_SAVE_SUFFIX)
                            )
                            .read_text("utf-8")
                            .splitlines()
                        )[0],
                        int(cot_inf[1]),
                        int(cot_inf[2]),
                    )
                    for i in range(0, int(idx_file.read_text("utf-8")))
                ]
            else:
                ipt(
                    "[#F03432 on #121110]缓存目录内应有的索引文件丢失",
                )
                sys.exit(-1)
            # frame_list = [
            #     (open(
            #         os.path.join(sys.argv[1], pat),
            #         "rb",
            #     ).read(), )
            #     for pat in sorted(
            #         [
            #             cii
            #             for cii in os.listdir(sys.argv[1])
            #             if os.path.isfile(cii) and cii.endswith(cache_file_suffix)
            #         ],
            #         key=lambda _x: int(_x.split(".")[0]),
            #     )
            # ]

            output_file_name = ipt("输出文件名：")

    output_path: str = format_ipt("输出地址：", os.path.isdir, "无法找到此地址。")[0]
    is_coloured: bool = format_ipt(
        "启用彩色解析：", bool_str, "请输入正确的布尔格式。"
    )[1]

    is_coloured_band: bool = format_ipt(
        "使用彩色竖线条而非盲文点阵：", bool_str, "请输入正确的布尔格式。"
    )[1]

    if random() <= 0.3:
        flashing_your_eye: bool = format_ipt(
            "闪瞎人眼：", bool_str, "请输入正确的布尔格式。"
        )[1]
    else:
        flashing_your_eye = False

    if frame_list is None:
        input_vedio_path: str = format_ipt(
            "视频文件地址：", os.path.isfile, "无法找到此文件。"
        )[0]

        # is_cached = format_ipt("启用缓存：", bool_str, "请输入正确的布尔格式。")[1]
        is_image_file_cached = format_ipt(
            "启用图片缓存：", bool_str, "请输入正确的布尔格式。"
        )[1]

        player_selector: str = ipt("玩家选择器：")

        t = time.time()

        total_frame_count, frame_list = vedio_frame_split(
            vedio_path=input_vedio_path,
            max_resolving_fps=20,
            resize=True,
            width=(180 if is_coloured_band else 210) if is_coloured else 200,
            height=120,
            resize_mode=ADAPT,
            output_path=(
                Path(os.path.join(output_path, "frames_cache/"))
                if is_image_file_cached
                else None
            ),
        )

        output_file_name = os.path.splitext(os.path.basename(input_vedio_path))[0]

        # if is_cached:
        #     pass
    else:
        player_selector: str = ipt("玩家选择器：")
        t = time.time()

    struct, size, end_pos = commands_to_structure(
        [
            SingleCommand(
                f"titleraw {player_selector} actionbar"
                + '{"rawtext":[{"text":"'
                + string.replace("\n", "\\n")
                + '\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n"}]}',
                tick_delay=1,
                annotation="由MVP生成",
            )
            for i, string in image_list_2_string(
                frame_list,
                is_coloured=is_coloured,
                is_coloured_band=is_coloured_band,
                rolling_length=35,
                flashing=flashing_your_eye,
            )
        ],
        max_height=32,
    )

    with open(
        os.path.abspath(os.path.join(output_path, f"{output_file_name}.mcstructure")),
        "wb+",
    ) as f:
        struct.dump(f)

    ipt(
        "转换用时：{tn}\t结构大小：{sz}\t终点位置：{ep}\n\n按下回车键退出".format(
            tn=time.time() - t, sz=size, ep=end_pos
        )
    )


# prt(__name__)

if __name__ == "__main__":
    freeze_support()
    if os.getenv(FILE_SAVE_SUFFIX + "_MAIN") == "True":
        ipt(
            "[#F03432 on #4E4C9C]这一行代码不应该被运行，如果碰到了这行提示，请关闭程序"
        )
    else:
        os.environ[FILE_SAVE_SUFFIX + "_MAIN"] = "True"
        main()
